package com.shuai.frame.config;


import com.shuai.frame.constant.RpcConstant;
import com.shuai.frame.factory.RegistryFactory;
import com.shuai.frame.registry.RegistryCenter;
import com.shuai.frame.utils.LoadConfigUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * 双检锁单例模式，控制配置对象的正确加载
 */
@Slf4j
public class XSRpcApplicationContext {
    private static volatile XSRpcConfig xsRpcConfig;

    private XSRpcApplicationContext() {
    }

    public static XSRpcConfig getXSRpConfig() {
        if (xsRpcConfig == null) {
            synchronized (XSRpcApplicationContext.class) {
                if (xsRpcConfig == null) {
                    xsRpcConfig = LoadConfigUtils.loadConfigToBean(XSRpcConfig.class, RpcConstant.RPC_CONFIG_PREFIX);
                }
            }
        }
        return xsRpcConfig;
    }

    public static void init() {
        log.info("初始化xs-rpc配置：{}", getXSRpConfig());
        RegistryCenter registryCenter = RegistryFactory.getRegistryCenter(getXSRpConfig().getRegistryCenterConfig().getRegistryType());
        registryCenter.init(getXSRpConfig().getRegistryCenterConfig());
        log.info("初始化注册中心：{}", getXSRpConfig().getRegistryCenterConfig());

        // 创建并注册shutdown Hook,JVM正常退出时执行一些操作如下线节点、关闭资源
        Runtime.getRuntime().addShutdownHook(new Thread(registryCenter::destroyService));
    }
}
